package com.fitness.service.serviceimpl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.fitness.mapper.WxMapper;
import com.fitness.model.Order;
import com.fitness.model.WxInformation;
import com.fitness.service.WxService;
import com.fitness.util.BasicsUtil;
import com.fitness.util.CommonUtil;
import com.fitness.util.DateUtil;
import com.fitness.util.JsonUtil;
import com.fitness.util.MyConfig;
import com.fitness.util.SignUtil;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

@Service
public class WxServiceImpl implements WxService{

	@Resource
	WxMapper wxMapper;

	@Transactional
	public String WxPaySign(Order order, HttpServletRequest request) {
		JsonUtil ju = new JsonUtil();
		Map<String, String> resp = null;
		String number32;
		if(order==null) return JsonUtil.blank(false,CommonUtil.ERROR_NONE, "提交的订单错误");
		if (("").equals(order.getOrderNumber())) {
			number32 = BasicsUtil.getOrderNumber32();
			order.setOrderNumber(number32);
		} else {
			number32 = order.getOrderNumber();
		}
		//先准备好一些转换数据-->double-->以分为单位的金额string
		String priceStr =  new Integer(new Double(order.getPriceTotle()).intValue()*100).toString();
		//构建与微信交互的数据
		MyConfig config = new MyConfig();
		WXPay wxpay = new WXPay(config);
		Map<String, String> data = new HashMap<String, String>();
		data.put("body", "健身订单支付");//这里填入标题 测试的时候打印出金额innerto.getTitle()+priceStr
		data.put("device_info", "WEB");//设备信息
		data.put("fee_type", "CNY");//货币种类
		data.put("total_fee", priceStr);//支付金额 这里先填1分
		data.put("spbill_create_ip", "112.74.62.52");//ip地址
		data.put("notify_url", "http://112.74.62.52:8080/fitnessclass/wx/h5/back");//支付回调地址 写死
		data.put("trade_type", "JSAPI");  //交易类型 我们默认为JSAPI交易
		data.put("openid",order.getOpenid());//获取支付用户的openid
		data.put("out_trade_no",number32);//传入订单号
		//data.put("out_trade_no",new Integer(RandomUtils.nextInt()).toString());//随机数
		try {
			resp = wxpay.unifiedOrder(data);
			System.out.println(WXPayUtil.mapToXml(resp));
			if("FAIL".equals(resp.get("return_code"))) return JsonUtil.blank(false,CommonUtil.ERROR_HANDLE,"预支付失败");
			resp.put("appid",config.getAppID());
			resp.put("timestamp", DateUtil.getTimeStramp().toString());//构建时间戳
			//resp.put("openid",innerto.getOpenid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//对统一支付再次进行签名
		String paySign = SignUtil.wx_md5(resp);
		resp.replace("sign",paySign);
		ju.setMsg("统一支付获取成功");
		ju.add(resp);
		if (order.getId()==0 ) {
			//订单数据存进数据库
			order.setTimeDetail(order.getDate()+" "+order.getStartTime()+":00");
			wxMapper.insertOrder(order);
		}
		System.out.println("______________________"+ju.getJson());
		return ju.getJson();
	}

	
	/**
	 * 微信支付h5 回调
	 * @throws Exception 
	 */
	@Override
	public String wxH5PayBack(HttpServletRequest request) throws Exception {
		// 支付结果通知的xml格式数据
				String notifyData = CommonUtil.inputToString(request);
				MyConfig config = new MyConfig();
				WXPay wxpay = new WXPay(config);
				Map<String, String> notifyMap;
				HashMap<String, String> resultMap = new HashMap<>();
				try {
					notifyMap = WXPayUtil.xmlToMap(notifyData);
					// 转换成map
					if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
						// 签名正确
						String time_end = DateUtil.formatString(notifyMap.get("time_end"));
						notifyMap.put("time_end", time_end);//将转换后的时间替换
						System.out.println(notifyMap.get("time_end"));
						notifyMap.put("out_trade_no", notifyMap.get("out_trade_no"));
						Order order = new Order();
						order.setOrderNumber(notifyMap.get("out_trade_no"));
						wxMapper.updateStates(order);//数据库操作
						
						resultMap.put("return_code", "SUCCESS");
						resultMap.put("return_msg", "ok");
						System.out.println(WXPayUtil.mapToXml(resultMap));
						// 进行处理。
						// 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
					}
					else {
						resultMap.put("return_code", "FALT");
						// 签名错误，如果数据里没有sign字段，也认为是签名错误
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return WXPayUtil.mapToXml(resultMap);  
	}


	@Override
	public void insertOpenid(WxInformation wxInformation) {
		wxMapper.insertOpenid(wxInformation);
		
	}


	@Override
	public Integer isInOpenid(WxInformation wxInformation) {
		Integer count = wxMapper.isInOpenid(wxInformation);
		return count;
	}



}
